package json

import (
	"github.com/anchore/grype/grype/match"
	"github.com/anchore/grype/grype/vulnerability"
)

type Cvss struct {
	BaseScore           float64  `json:"baseScore"`
	ExploitabilityScore *float64 `json:"exploitabilityScore,omitempty"`
	ImpactScore         *float64 `json:"impactScore,omitempty"`
	Vector              string   `json:"vector"`
}

type Vulnerability struct {
	ID             string   `json:"id"`
	Severity       string   `json:"severity,omitempty"`
	Links          []string `json:"links,omitempty"`
	Description    string   `json:"description,omitempty"`
	CvssV2         *Cvss    `json:"cvssV2,omitempty"`
	CvssV3         *Cvss    `json:"cvssV3,omitempty"`
	FixedInVersion string   `json:"fixedInVersion,omitempty"`
}

func NewVulnerability(m match.Match, metadata *vulnerability.Metadata) Vulnerability {
	if metadata == nil {
		return Vulnerability{
			ID: m.Vulnerability.ID,
		}
	}

	var cvssV2 *Cvss
	if metadata.CvssV2 != nil {
		var exploitability, impact *float64
		if metadata.CvssV2.ExploitabilityScore > 0 {
			exploitability = &metadata.CvssV2.ExploitabilityScore
		}
		if metadata.CvssV2.ImpactScore > 0 {
			impact = &metadata.CvssV2.ImpactScore
		}
		cvssV2 = &Cvss{
			BaseScore:           metadata.CvssV2.BaseScore,
			ExploitabilityScore: exploitability,
			ImpactScore:         impact,
			Vector:              metadata.CvssV2.Vector,
		}
	}

	var cvssV3 *Cvss
	if metadata.CvssV3 != nil {
		var exploitability, impact *float64
		if metadata.CvssV3.ExploitabilityScore > 0 {
			exploitability = &metadata.CvssV3.ExploitabilityScore
		}
		if metadata.CvssV3.ImpactScore > 0 {
			impact = &metadata.CvssV3.ImpactScore
		}
		cvssV3 = &Cvss{
			BaseScore:           metadata.CvssV3.BaseScore,
			ExploitabilityScore: exploitability,
			ImpactScore:         impact,
			Vector:              metadata.CvssV3.Vector,
		}
	}

	return Vulnerability{
		ID:             m.Vulnerability.ID,
		Severity:       metadata.Severity,
		Links:          metadata.Links,
		Description:    metadata.Description,
		CvssV2:         cvssV2,
		CvssV3:         cvssV3,
		FixedInVersion: m.Vulnerability.FixedInVersion,
	}
}
